// http://blog.codility.com/2012/04/pi-2012-codility-programming.html

#include <vector>
#include <cmath>
typedef std::vector<int> Vector;
int findBigger(const Vector& a, const Vector& maxIndices, int maxIndex, int value, int d)
{
    while (d != maxIndex && a[d] <= value)
    {
        d = maxIndices[d];
    }
    return d;
}
Vector array_closest_ascenders (const Vector &a)
{
    const int Size = (int)a.size();
    const int MaxIndex = Size * 3;
    Vector leftMax(Size, MaxIndex);
    Vector rightMax(Size, MaxIndex);
    for (int d = 1, rd = Size - 2; d < Size; ++d, --rd)
    {
        leftMax[d] = findBigger(a, leftMax, MaxIndex, a[d], d - 1);
        rightMax[rd] = findBigger(a, rightMax, MaxIndex, a[rd], rd + 1);
    }
    // convert to distance
    for (int i = 0; i < Size; ++i)
    {
        leftMax[i] = leftMax[i] == rightMax[i] ?
            0 :
        std::min(abs(i - leftMax[i]), rightMax[i] - i);
    }
    return leftMax;
}
